package com.huawei.cloud.phone.management.infrastructure.connection;

import com.huawei.cloud.phone.management.domain.connection.Connection;
import com.huawei.cloud.phone.management.domain.connection.ConnectionGateway;
import com.huawei.cloud.phone.management.domain.connection.ConnectionStatus;
import com.huawei.cloud.phone.management.domain.phone.Phone;
import com.huawei.cloud.phone.management.infrastructure.db.mapper.ConnectionMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@AllArgsConstructor
@Component
public class ConnectionGatewayImpl implements ConnectionGateway {
    private final ConnectionMapper connectionMapper;

    @Override
    public boolean addConnection(@NonNull Connection connection) {
        try {
            return connectionMapper.addConnection(connection) != 0;
        } catch (Exception e) {
            log.error("add connection failed.", e);
            return false;
        }
    }

    @Override
    public boolean updateConnection(@NonNull Connection connection) {
        return connectionMapper.updateConnection(connection) == 1;
    }

    @Override
    public boolean updateStatus(@NonNull String connectionId, @NonNull ConnectionStatus origin, @NonNull ConnectionStatus target) {
        return connectionMapper.updateStatus(connectionId, origin, target) == 1;
    }

    @Override
    public Optional<Connection> getConnection(@NonNull String userPhoneId) {
        return Optional.ofNullable(connectionMapper.getConnectionByUserPhone(userPhoneId));
    }

    @Override
    public Optional<Connection> getConnectionByPhoneId(@NonNull String phoneId) {
        return Optional.ofNullable(connectionMapper.getConnectionByPhone(phoneId));
    }

    @Override
    public void deleteConnection(@NonNull String userPhoneId) {
        connectionMapper.deleteConnection(userPhoneId);
    }


    @Override
    public List<Phone> getAllUsingPhones() {
        List<String> usingPhonesId = connectionMapper.getUsingPhoneIds();
        return usingPhonesId.stream().map(phoneId -> {
                    Phone phone = new Phone();
                    phone.setPhoneId(phoneId);
                    return phone;
                })
                .collect(Collectors.toList());
    }

    @Override
    public int maintainStatus(@NonNull ConnectionStatus origin, @NonNull ConnectionStatus target) {
        return connectionMapper.maintainStatus(origin, target);
    }
}
